﻿using System;
using System.Linq;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;

namespace Docsbox.Layouts.Docsbox
{
    public partial class ElectronicAuditForm : LayoutsPageBase
    {
        private static string _listId;
        private static string _itemId;
        private static SPListItem _listItem;
        private static string _accountName;
        private static string ValidGroupName = "Auditors";
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlMeta meta = new HtmlMeta();
            meta.HttpEquiv = "X-UA-Compatible";
            meta.Content = "IE=EmulateIE7";
            this.Header.Controls.AddAt(0,meta);
            if (!IsPostBack)
            {
                SPUser user = SPContext.Current.Web.CurrentUser;
                if (!ValidateUserPermission(user))
                {
                    SetReadOnly();
                }


                _listId = Request.QueryString["List"];
                _itemId = Request.QueryString["ID"];
                LoadAccountDetails();
                //LoadDocumentList();
            }
        }

        private void SetReadOnly()
        {
            this.AddressConfirmationCheckBox.Enabled = false;
            this.AffordabilityCheckBox.Enabled = false;
            this.BankStatementCheckBox.Enabled = false;
            this.CDPCoverCheckBox.Enabled = false;
            this.CreditCheckCheckBox.Enabled = false;
            this.DepositRequirementCheckBox.Enabled = false;
            this.DriverLicenseCheckBox.Enabled = false;
            this.InsuranceCheckBox.Enabled = false;
            this.RPWCheckBox.Enabled = false;
            this.VisaResidencyCheckBox.Enabled = false;
            this.WagesSlipCheckBox.Enabled = false;

            this.txtConfirmationOfAddressComment.Enabled = false;
            this.AffordabilityComment.Enabled = false;
            this.txtBankStatementComment.Enabled = false;
            this.CDPCoverComment.Enabled = false;
            this.CreditCheckComment.Enabled = false;
            this.DepositRequirementComment.Enabled = false;
            this.txtDriverLicenseComment.Enabled = false;
            this.InsuranceComment.Enabled = false;
            this.RPWComment.Enabled = false;
            this.VisaResidencyComment.Enabled = false;
            this.WagesSlipComment.Enabled = false;

            this.txtAuditComment.Enabled = false;

            this.btnAmendmentsRequired.Enabled = false;
            this.btnCancel.Enabled = false;
            this.btnComplete.Enabled = false;
            this.btnSave.Enabled = false;

            this.chbCheckAll.Disabled = true;
        }

        private bool ValidateUserPermission(SPUser user)
        {
            SPGroup auditorGroup = SPContext.Current.Web.SiteGroups[ValidGroupName];
            if(auditorGroup != null)
            {
                bool result = user.Groups.Cast<SPGroup>().Select(x => x.Name).Contains(ValidGroupName);
                return result;
            }
            else
            {
                //the auditorGroup doesn't exist
                throw new Exception(string.Format("Auditor Required Group {0} doesn't exist. Please create this group in this web and assign auditors to this group."));
            }
        }

        private void LoadAccountDetails()
        {
            if (!String.IsNullOrEmpty(_listId) && !string.IsNullOrEmpty(_itemId))
            {
                Guid listId = new Guid(_listId);
                int itemId = Convert.ToInt32(_itemId); 
                SPWeb current = this.Web;
                SPList projects = current.Lists[listId];
                _listItem = projects.GetItemById(itemId);
                LoadItemData(_listItem);
            }
        }

        private void LoadItemData(SPListItem item)
        {
            var documentName = Common.ConvertFieldToString(item[Common.FieldMTFNo], FieldType.Text);
            _accountName = documentName;
            lblTitle.Text = documentName;
            lblFirstName.Text = Common.ConvertFieldToString(item[Common.FieldFirstName], FieldType.Text);
            lblSurname.Text = Common.ConvertFieldToString(item[Common.FieldSurname], FieldType.Text);
            lblRegNo.Text = Common.ConvertFieldToString(item[Common.FieldRegNo], FieldType.Text);
            lblStatus.Text = Common.ConvertFieldToString(item[Common.FieldAccountStatus], FieldType.Lookup);
            lblContractDate.Text = Common.ConvertFieldToString(item[Common.FieldContractDate], FieldType.DateOnly);
            lblRevisionDate.Text = Common.ConvertFieldToString(item[Common.FieldRevisionDate], FieldType.DateOnly);
            lblComments.Text = Common.ConvertFieldToString(item[Common.FieldAccountComment], FieldType.Note);

            string status = Common.ConvertFieldToString(item[Common.FieldAccountStatus], FieldType.Lookup);

            if(status.Equals(Common.StatusCompleted, StringComparison.CurrentCultureIgnoreCase))
                SetReadOnly();

            //load audit checklist data
            DriverLicenseCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldDriverLicenceApproved]);
            BankStatementCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldBankStatementApproved]);
            AddressConfirmationCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldConfirmationOfAddressApproved]);
            WagesSlipCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldWagesSlipApproved]);
            VisaResidencyCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldVisaResidencyApproved]);
            CreditCheckCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldCreditCheckApproved]);
            InsuranceCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldInsuranceApproved]);
            RPWCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldRPWApproved]);
            CDPCoverCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldCDPCoverApproved]);
            AffordabilityCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldAffordabilityApproved]);
            DepositRequirementCheckBox.Checked = Common.ConvertFieldToBoolean(item[Common.FieldDepositRequirementApproved]);

            txtDriverLicenseComment.Text = Common.ConvertFieldToString(item[Common.FieldDriverLicenseComment],
                                                                       FieldType.Text);
            txtBankStatementComment.Text = Common.ConvertFieldToString(item[Common.FieldBankStatementComment],
                                                                       FieldType.Text);
            txtConfirmationOfAddressComment.Text = Common.ConvertFieldToString(item[Common.FieldConfirmationOfAddressComment],
                                                                       FieldType.Text);
            WagesSlipComment.Text = Common.ConvertFieldToString(item[Common.FieldWagesSlipComment],
                                                                       FieldType.Text);
            VisaResidencyComment.Text = Common.ConvertFieldToString(item[Common.FieldVisaResidencyComment],
                                                                       FieldType.Text);
            CreditCheckComment.Text = Common.ConvertFieldToString(item[Common.FieldCreditCheckComment],
                                                                       FieldType.Text);
            InsuranceComment.Text = Common.ConvertFieldToString(item[Common.FieldInsuranceComment],
                                                                       FieldType.Text);
            RPWComment.Text = Common.ConvertFieldToString(item[Common.FieldRPWComment],
                                                                       FieldType.Text);
            CDPCoverComment.Text = Common.ConvertFieldToString(item[Common.FieldCDPCoverComment],
                                                                       FieldType.Text);
            AffordabilityComment.Text = Common.ConvertFieldToString(item[Common.FieldAffordabilityComment],
                                                                       FieldType.Text);
            DepositRequirementComment.Text = Common.ConvertFieldToString(item[Common.FieldDepositRequirementComment],
                                                                       FieldType.Text);

            txtAuditComment.Text = Common.ConvertFieldToString(item[Common.FieldAuditComment], FieldType.Text);

            //load document list, open the first by default
            LoadTreeViewList(documentName);
        }
        protected void pdTreeView_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (projectDocTreeView.SelectedNode.Depth ==1)
            {
                RefreshPDFViewer(projectDocTreeView.SelectedNode.Text);
            }
        }
        private string EmbedString(string docPath)
        {
            return string.Format("<embed src=\"{0}\" type=\"application/pdf\" width=\"100%\"height=\"560px\" />", docPath);
        }

        private void LoadTreeViewList(string documentName)
        {
            string folderName = documentName.Substring(documentName.Length - 2);
            SPWeb current = this.Web;
            SPList documents = current.Lists[Common.ListDocuments];
            SPQuery query = new SPQuery(documents.DefaultView);
            query.QueryThrottleMode = SPQueryThrottleOption.Override;
            query.Query = GetQueryString(documentName);
            SPFolder folder = documents.RootFolder.SubFolders[folderName];
            query.Folder = folder;
            query.ViewAttributes += " Scope=\"Recursive\"";
            
            SPSecurity.RunWithElevatedPrivileges(delegate()
                                                     {
                                                      
                                                         SPListItemCollection collection = documents.GetItems(query);
                                                    
                                                         TreeNode docRoot = new TreeNode();
                                                        docRoot.Text = documentName;
                                                        string docName = AddDocument(docRoot, collection);
                                                        projectDocTreeView.Nodes.Add(docRoot);
                                                        RefreshPDFViewer(docName);                                                       
                                                     });



        }

        private void RefreshPDFViewer(string docName)
        {
            if(_accountName.Length > 2)//check accountname is not empty
            {
                 string folder = _accountName.Substring(_accountName.Length - 2);

                string documentUrl = string.Format("{0}/{1}/{2}/{3}", this.Web.Url, Common.ListDocuments,folder,docName);
                this.embedPDFViewer.Text = EmbedString(documentUrl);               
            }

        }

        /// <summary>
        /// add all documents to the list and return the first documents name 
        /// </summary>
        /// <param name="docRoot"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        private string AddDocument(TreeNode docRoot, SPListItemCollection collection)
        {
            string firstDocumentName = string.Empty;
            foreach (SPListItem item in collection)
            {
                if (String.IsNullOrEmpty(firstDocumentName))
                {
                    firstDocumentName = item.Name;
                }
                TreeNode node = new TreeNode() { Text = item.Name };
                docRoot.ChildNodes.Add(node);
            }
            return firstDocumentName;
        }
        private string GetQueryString(string filter)
        {
            String query = @"<Where><Eq><FieldRef Name='{1}' /><Value Type='Lookup'>{0}</Value></Eq></Where>";
            return string.Format(query, filter,Common.FieldAccountLookup);
        }


        #region click events

        public void btnSave_Click(object sender, EventArgs e)
        {
            UpdateAccountDetails();
            SaveChanges();
            ClosePopUp();
        }

        private void SaveChanges()
        {
            this.Web.AllowUnsafeUpdates = true;
            _listItem.Update();
            this.Web.AllowUnsafeUpdates = false;
        }

        private void UpdateAccountDetails()
        {
            _listItem[Common.FieldDriverLicenceApproved] = DriverLicenseCheckBox.Checked;
            _listItem[Common.FieldBankStatementApproved] = BankStatementCheckBox.Checked;
            _listItem[Common.FieldConfirmationOfAddressApproved] = AddressConfirmationCheckBox.Checked;
            _listItem[Common.FieldWagesSlipApproved] = WagesSlipCheckBox.Checked;
            _listItem[Common.FieldVisaResidencyApproved] = VisaResidencyCheckBox.Checked;
            _listItem[Common.FieldCreditCheckApproved] = CreditCheckCheckBox.Checked;
            _listItem[Common.FieldInsuranceApproved] = InsuranceCheckBox.Checked;
            _listItem[Common.FieldRPWApproved] = RPWCheckBox.Checked;
            _listItem[Common.FieldCDPCoverApproved] = CDPCoverCheckBox.Checked;
            _listItem[Common.FieldAffordabilityApproved] = AffordabilityCheckBox.Checked;
            _listItem[Common.FieldDepositRequirementApproved] = DepositRequirementCheckBox.Checked;

            _listItem[Common.FieldDriverLicenseComment] = txtDriverLicenseComment.Text;
            _listItem[Common.FieldBankStatementComment] = txtBankStatementComment.Text;
            _listItem[Common.FieldConfirmationOfAddressComment] = txtConfirmationOfAddressComment.Text;
            _listItem[Common.FieldWagesSlipComment] = WagesSlipComment.Text;
            _listItem[Common.FieldVisaResidencyComment] = VisaResidencyComment.Text;
            _listItem[Common.FieldCreditCheckComment] = CreditCheckComment.Text;
            _listItem[Common.FieldInsuranceComment] = InsuranceComment.Text;
            _listItem[Common.FieldRPWComment] = RPWComment.Text;
            _listItem[Common.FieldCDPCoverComment] = CDPCoverComment.Text;
            _listItem[Common.FieldAffordabilityComment] = AffordabilityComment.Text;
            _listItem[Common.FieldDepositRequirementComment] = DepositRequirementComment.Text;

            _listItem[Common.FieldAuditComment] = DepositRequirementComment.Text;
            
        }

        public void btnAmendmentsRequired_Click(object sender, EventArgs e)
        {
                UpdateAccountDetails();
                _listItem[Common.FieldAccountStatus] = Common.GetLookupStatus(this.Web, Common.StatusAmendmentRequired);
                SaveChanges();
                ClosePopUp();  
        }

        public void btnComplete_Click(object sender, EventArgs e)
        {
            if(AllCheckboxTicked())
            {
                UpdateAccountDetails();
                _listItem[Common.FieldAccountStatus] = Common.GetLookupStatus(this.Web, Common.StatusCompleted);
                SaveChanges();
                ClosePopUp();              
            }
  
        }

        private bool AllCheckboxTicked()
        {
            if (AddressConfirmationCheckBox.Checked && 
                AffordabilityCheckBox.Checked && 
                BankStatementCheckBox.Checked && 
                CDPCoverCheckBox.Checked && 
                CreditCheckCheckBox.Checked && 
                DepositRequirementCheckBox.Checked && 
                DriverLicenseCheckBox.Checked && 
                InsuranceCheckBox.Checked && 
                RPWCheckBox.Checked && 
                VisaResidencyCheckBox.Checked && 
                WagesSlipCheckBox.Checked)
                return true;
            return false;
        }

        #endregion


        private void ClosePopUp()
        {
            Context.Response.Write("<Script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }
    }

}
